<?php

namespace app\common\Jobs;

use app\common\exception\BaseException;
use app\common\model\DealerGoodsSpec;
use app\common\model\GoodsSpec;
use app\company\model\CompanyOrderDetail;
use app\company\model\CompanyTransferOrderDetail;
use app\company\model\DealerOrderDetail;
use app\company\model\ReportGoodsOut;
use think\queue\Job;

class ReportGoodsOutJob
{
    public function fire(Job $job, $orderInfo): void
    {
        $goods_spec_model = new DealerGoodsSpec();
        // 具体业务逻辑


        if ($orderInfo['type'] == 1) {
            //销售出库
            // 查询订单详情

            try {
                $orderIds = explode(',', $orderInfo['company_order_ids']);
                CompanyOrderDetail::where('company_order_id', 'in', $orderIds)
                    ->field('dealer_goods_id,dealer_goods_spec_id,num,sale_price * num as sale_money')
                    ->select()
                    ->each(function ($vo) use ($orderInfo, &$res) {
                        $res = $this->dealJob($vo, $orderInfo);
                    });
            } catch (\Exception $e) {
                print_r($e->getMessage());
                throw  new BaseException(['message' => $e->getMessage()]);
            }
        } else if ($orderInfo['type'] == 2) {
            //采退出库

            $orderIds = explode(',', $orderInfo['dealer_order_ids']);

            DealerOrderDetail::where('dealer_order_id', 'in', $orderIds)
                ->field('dealer_goods_id,dealer_goods_spec_id,num,purchase_price,purchase_price * num as sale_money')
                ->select()
                ->each(function ($vo) use ($orderInfo, &$res) {

                    try {
                        $res = $this->dealJob($vo, $orderInfo);
                    } catch (\Exception $e) {
                        throw  new BaseException(['message' => $e->getMessage()]);
                    }
                });
        } else {
            //调拨出库生成
            try {
                $orderIds = explode(',', $orderInfo['transfer_order_ids']);
                CompanyTransferOrderDetail::where('t_oid', 'in', $orderIds)
                    ->field('dealer_goods_id,dealer_goods_spec_id,transfer_num as num')
                    ->select()
                    ->each(function ($vo) use ($orderInfo, &$res, $goods_spec_model) {
                     
                        $goods_spec_data =  $goods_spec_model->field('sale_price')->where('id', $vo->dealer_goods_spec_id)
                        ->withTrashed()->find();
                        $vo->sale_money = $goods_spec_data->sale_price * $vo->num;

                        $res = $this->dealJob($vo, $orderInfo);
                    });
            } catch (\Exception $e) {
                print_r($e->getMessage().$e->getLine());
                throw  new BaseException(['message' => $e->getMessage()]);
            }
        }
        $job->delete();
        //    if ($res) {
        //     $job->delete(); 
        //    } else {
        //        $job->release(5); // 重新放入队列，延迟5秒执行
        //    }
    }

    /**
     * 处理任务
     */
    private function dealJob($vo, $orderInfo): ReportGoodsOut|int|string
    {
        $model     = new ReportGoodsOut();
        $goods     = $vo->goods()->field('dealer_id,cate_id')->withTrashed()->find();
        $unit_type = $vo->goodsSpec()->withTrashed()->value('unit_type');
        $dealer_id = $goods->dealer_id;

        $data = [
            'small_unit_id'  => $unit_type == 1 ? $vo->dealer_goods_spec_id : 0,
            'big_unit_id'    => $unit_type == 2 ? $vo->dealer_goods_spec_id : 0,
            'middle_unit_id' => $unit_type == 3 ? $vo->dealer_goods_spec_id : 0,
            'type' => $orderInfo['type'], //1销售出库单 2采退出库单
        ];


        // 查询记录
        $date = date('Y-m-d', strtotime($orderInfo['update_time']));
        $where = [
            ['dealer_id', '=', $dealer_id],
            ['company_id', '=', $orderInfo['company_id']],
            ['dealer_goods_id', '=', $vo->dealer_goods_id],
            ['time', '=',  $date],
            ['type', '=', $orderInfo['type']]
        ];
        $record = $model->where($where)->find();
        // print_r('--record-');

        if ($record) {
            $res = $model->where('id', $record->id)
                ->inc('small_unit_out_value', $unit_type == 1 ? $vo->sale_money : 0)
                ->inc('small_unit_out_num', $unit_type == 1 ? $vo->num : 0)
                ->inc('middle_unit_out_value', $unit_type == 2 ? $vo->sale_money : 0)
                ->inc('middle_unit_out_num', $unit_type == 2 ? $vo->num : 0)
                ->inc('big_unit_out_value', $unit_type == 3 ? $vo->sale_money : 0)
                ->inc('big_unit_out_num', $unit_type == 3 ? $vo->num : 0)
                ->update($data);
        } else {

            $data['company_id']            = $orderInfo['company_id'];
            $data['dealer_id']             = $dealer_id;
            $data['dealer_goods_id']       = $vo->dealer_goods_id;
            $data['dealer_cate_id']        = $goods->cate_id;
            $data['small_unit_out_value']  = $unit_type == 1 ? $vo->sale_money : 0;
            $data['small_unit_out_num']    = $unit_type == 1 ? $vo->num : 0;
            $data['middle_unit_out_value'] = $unit_type == 2 ? $vo->sale_money : 0;
            $data['middle_unit_out_num']   = $unit_type == 2 ? $vo->num : 0;
            $data['big_unit_out_value']    = $unit_type == 3 ? $vo->sale_money : 0;
            $data['big_unit_out_num']      = $unit_type == 3 ? $vo->num : 0;
            $data['time']                  =  $date;
            // $data['create_time'] = time();
            $data['create_time'] = strtotime($orderInfo['update_time']);

            try {
                $res            = $model->insert($data);
            } catch (\Exception $e) {
                print_r($e->getMessage());
            }
        }
        return $res;
    }

    public function failed($data)
    {
        // ...任务达到最大重试次数后，失败了
    }
}
